package com.smartwebx.ha.web.admin.module.screen.report;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 连接工具类
 * 
 * ConnUtils类声明为final类说明此类不可以被继承
 * 
 * @author Dream~天涯
 * 
 */
public final class ConnUtils {
    private static String url ;
    private static String user ;
    private static String password ;

    /**
     * 说明要访问此类只能通过static或单例模式
     */
    ConnUtils() {
    }

    // 注册驱动 (只做一次)
    static {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * 获取Connection对象
     * 
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
    	Properties props = new Properties();
		InputStream in;
		try {
			in = new BufferedInputStream (new FileInputStream(this.getClass().getResource("/").getPath().replace("classes", "")+"/config.properties"));
			props.load(in);
			url = props.getProperty ("db.oracle.url");
			user = props.getProperty ("db.oracle.user");
			password = props.getProperty ("db.oracle.pass");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
        return DriverManager.getConnection(url, user, password);
    }
    /**
     * 释放资源
     * 
     * @param rs
     * @param st
     * @param conn
     */
    public static void free(ResultSet rs, Statement st, Connection conn) {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (st != null)
                    st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (conn != null)
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
            }
        }
    }
    public static void main(String[] args) {
    	ConnUtils c = new ConnUtils();
    	try {
			c.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}